package main

import (
	"bufio"
	"fmt"
	"gitee.com/shu2015626/go_start_imooc/chapter07-error_resource/fib"
	"os"
)

//defer的作用：在return之前执行
//defer有个栈：先进后出
func tryDefer() {
	//defer fmt.Println(1)
	//defer fmt.Println(2)
	//fmt.Println(3)
	////return
	////panic("error occurred")
	//fmt.Println(4)

	// 参数在defer语句时计算
	for i := 0; i < 100; i++ {
		defer fmt.Println(i)
		if i == 30 {
			panic("printed too many")
		}
	}
}

func writeFile(filename string) {
	//file, err := os.Create(filename)
	file, err := os.OpenFile(filename, os.O_EXCL|os.O_CREATE, 0666)

	//err = errors.New("this is a custom error")
	if err != nil {
		//panic(err)
		//fmt.Println("file already exists")
		//fmt.Println("Error: ", err.Error())
		//fmt.Println("Error: ", err)
		if pathError, ok := err.(*os.PathError); !ok {
			panic(err)
		} else {
			fmt.Printf("%s, %s, %s \n", pathError.Op, pathError.Path, pathError.Err)
		}
		return
	}
	defer file.Close()

	writer := bufio.NewWriter(file)
	defer writer.Flush()

	f := fib.Fibonacci()
	for i := 0; i < 20; i++ {
		fmt.Fprintln(writer, f())
	}

}

func main() {
	//tryDefer()

	writeFile("chapter07-error_resource/errorhandling/defer/fib.txt")
}
